const db = uniCloud.database();
const stage_collection = db.collection('study_stage');
const subject_collection = db.collection('subject');
const examRecored_collection = db.collection('exam_record');
const examScore_collection = db.collection('exam_score');

module.exports = {
	_before() {
		// 可以在这里添加一些前置通用逻辑，当前为空
	},
	/**
	 * 获取学生grade对应的subject
	 * @returns {object[]} 返回包含学生subject列表
	 */
	async getSubjectList(grade) {
		try {
			// 1. 先从study_stage集合根据grade查询相关记录
			const stageRes = await stage_collection.where({
				name: grade
			}).get();

			if (stageRes.data.length === 0) {
				return {
					message: '未找到对应grade的study_stage信息'
				};
			}

			const subjectIds = stageRes.data[0].subject_ids;

			// 2. 再依据subjectIds从subject集合获取科目详情
			const subjectInfo = subjectIds.map(id => {
				return subject_collection.where({
					id: id
				}).get();
			});
			// Promise.all会同时触发这些 Promise 开始执行
			const subjectResults = await Promise.all(subjectInfo);
			const subjects = subjectResults.flatMap(result => result.data);
			return subjects;
		} catch (e) {
			return {
				error: e.message
			};
		}
	},
	/**
	 * 根据studentId/grade/examName/examData更新exam_record信息
	 * @param {object} examInfo - 新的考试记录
	 */
	async updateExamRecord(examInfo) {
		try {
			const {
				student_id,
				grade,
				examName,
				examDate
			} = examInfo;

			// 移除传入的examInfo中的scoreList字段，并单独赋值给relative，用于后续exam_score表的更新
			const {
				scoreList,
				...newExamInfo
			} = examInfo;

			// 查找是否存在匹配这些条件的表项
			const query = examRecored_collection.where({
				student_id,
				grade,
				examName,
				examDate
			});
			const countRes = await query.get();
			console.log('countRes', countRes)
			//如果存在表项，就更新；否则就新增
			if (countRes.data.length > 0) {
				// 存在则更新
				const recordId = countRes.data[0]._id;
				const updateRes = await examRecored_collection.doc(recordId).update(newExamInfo);
				console.log('updateRes', updateRes)
				console.log('recordId', recordId)
				if (scoreList && scoreList.length > 0) {
					const scoreUpdatePromises = scoreList.map((subjectScore, index) => {
						return examScore_collection.where({
							exam_record_id: recordId
						}).update(subjectScore);
					});
					await Promise.all(scoreUpdatePromises);
				}
				return {
					success: true,
					message: 'examInfo更新成功'
				};
			} else {
				// 添加exam_recored表中的id，区分功能：_id用于云数据库操作，id可后续用于本地数据
				// 获取student表中最后一条数据的id
				const lastRecord_record = await examRecored_collection.orderBy('_id', 'desc').limit(1).get();
				const lastRecord_score = await examScore_collection.orderBy('_id', 'desc').limit(1).get();
				let record_newId;
				if (lastRecord_record.data.length > 0) {
					let lastId_record = lastRecord_record.data[0].id;
					let lastId_score = lastRecord_score.data[0].id;
					record_newId_record = lastId_record + 1;
					record_newId_score = lastId_score + 1;
				} else {
					record_newId_record = 222222;
					record_newId_score = 333333;
				}
				const newExamInfo_id = {
					...newExamInfo,
					id: record_newId_record
				};
				console.log('newExamInfo_id', newExamInfo_id)
				// 不存在则新增
				const addRes = await examRecored_collection.add(newExamInfo_id);
				console.log('addRes', addRes)
				const newRecordId = addRes.id;

				if (scoreList && scoreList.length > 0) {
					const updatedScoreList = scoreList.map((scoreItem, index) => {
						return {
							...scoreItem,
							exam_record_id: newRecordId,
							id: record_newId_score + index
						};
					});
					console.log('updatedScoreList', updatedScoreList)
					const scoreUpdatePromises = updatedScoreList.map(async (subjectScore) => {
						console.log('subjectScore', subjectScore)
						return examScore_collection.add(subjectScore);
					});
					await Promise.all(scoreUpdatePromises);
				}
				return {
					success: true,
					message: 'examInfo新增成功'
				};
			}
		} catch (e) {
			return {
				error: e.message
			};
		}
	},
};